"use client"

import React, { useState, useMemo } from 'react'
import { Plus } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { useProjects } from '@/hooks/project'
import { useAuth } from '@/hooks/useAuth'
import { ProjectFormDialog } from '@/app/project/ProjectFormDialog'
import { ProjectDetailDialog } from '@/app/project/ProjectDetailDialog'
import { ProjectTable } from '@/app/project/ProjectTable'
import { ProjectFilters } from '@/app/project/ProjectFilters'
import type { Project } from '@/types/project'

// 主组件
export default function ProjectManagement() {
  const { user } = useAuth()
  const {
    projects,
    loading,
    error,
    canCreateProject,
    canEditProject,
    canDeleteProject,
    fetchProjects,
    deleteProject,
    clearError
  } = useProjects()

  // 状态管理
  const [showCreateDialog, setShowCreateDialog] = useState(false)
  const [showEditDialog, setShowEditDialog] = useState(false)
  const [showDetailDialog, setShowDetailDialog] = useState(false)
  const [selectedProject, setSelectedProject] = useState<Project | null>(null)

  // 筛选状态
  const [searchTerm, setSearchTerm] = useState('')
  const [statusFilter, setStatusFilter] = useState('all')
  const [actualSearchTerm, setActualSearchTerm] = useState('')

  // 根据筛选条件过滤项目
  const filteredProjects = useMemo(() => {
    if (!Array.isArray(projects)) return []
    
    return projects.filter(project => {
      // 搜索项目名称、描述、作物类型、地点和项目负责人
      const searchMatch = !actualSearchTerm || 
        project.name.toLowerCase().includes(actualSearchTerm.toLowerCase()) ||
        project.description.toLowerCase().includes(actualSearchTerm.toLowerCase()) ||
        (project.crop_type && project.crop_type.toLowerCase().includes(actualSearchTerm.toLowerCase())) ||
        (project.location && project.location.toLowerCase().includes(actualSearchTerm.toLowerCase())) ||
        (project.manager && project.manager.toLowerCase().includes(actualSearchTerm.toLowerCase()))
      
      // 状态筛选
      const statusMatch = statusFilter === 'all' || project.status === statusFilter
      
      return searchMatch && statusMatch
    })
  }, [projects, actualSearchTerm, statusFilter])

  // 处理搜索
  const handleSearch = () => {
    setActualSearchTerm(searchTerm)
  }

  // 处理删除项目
  const handleDeleteProject = async (project: Project) => {
    const result = await deleteProject(project.id)
    if (result.success) {
      // 删除成功，列表会自动更新
    }
  }

  // 处理查看项目详情
  const handleViewProject = (project: Project) => {
    setSelectedProject(project)
    setShowDetailDialog(true)
  }

  // 处理编辑项目
  const handleEditProject = (project: Project) => {
    setSelectedProject(project)
    setShowEditDialog(true)
  }

  return (
    <div className="space-y-2">
      {/* 页面标题 */}
      <Card>
        <CardHeader>
          <div className="flex justify-between items-center">
            <div>
              <CardTitle className="text-1xl">项目管理</CardTitle>
              <p className="text-gray-600 mt-1">
                {user?.laboratory_name ? `${user.laboratory_name} - ` : ''}
                管理和查看实验室项目
              </p>
            </div>
            {canCreateProject && (
              <Button onClick={() => setShowCreateDialog(true)}>
                <Plus className="w-4 h-4 mr-2" />
                创建项目
              </Button>
            )}
          </div>
        </CardHeader>
      </Card>

      {/* 错误信息 */}
      {error && (
        <div className="bg-red-50 border border-red-200 rounded-lg p-4">
          <p className="text-red-600">{error}</p>
          <Button variant="ghost" size="sm" onClick={clearError} className="mt-2">
            关闭
          </Button>
        </div>
      )}

      {/* 筛选组件 */}
      <Card>
        <CardContent className="pt-6">
          <ProjectFilters
            searchTerm={searchTerm}
            statusFilter={statusFilter}
            onSearchChange={setSearchTerm}
            onStatusChange={setStatusFilter}
            onSearch={handleSearch}
          />
        </CardContent>
      </Card>

      {/* 项目列表 */}
      {loading ? (
        <div className="flex justify-center items-center py-12">
          <div className="text-gray-500">加载中...</div>
        </div>
      ) : filteredProjects.length === 0 ? (
        <Card>
          <CardContent className="text-center py-12">
            <p className="text-gray-500 mb-4">
              {Array.isArray(projects) && projects.length === 0 ? '暂无数据，请先创建项目' : '没有找到匹配的项目'}
            </p>
            {canCreateProject && Array.isArray(projects) && projects.length === 0 && (
              <Button onClick={() => setShowCreateDialog(true)}>
                <Plus className="w-4 h-4 mr-2" />
                创建第一个项目
              </Button>
            )}
          </CardContent>
        </Card>
      ) : (
        <Card>
          <CardContent className="p-0">
            <ProjectTable
              projects={filteredProjects}
              canEditProject={canEditProject}
              canDeleteProject={canDeleteProject}
              onViewProject={handleViewProject}
              onEditProject={handleEditProject}
              onDeleteProject={handleDeleteProject}
            />
          </CardContent>
        </Card>
      )}

      {/* 对话框 */}
      <ProjectFormDialog
        isOpen={showCreateDialog}
        onClose={() => setShowCreateDialog(false)}
        onSuccess={() => fetchProjects()}
      />

      <ProjectFormDialog
        project={selectedProject || undefined}
        isOpen={showEditDialog}
        onClose={() => {
          setShowEditDialog(false)
          setSelectedProject(null)
        }}
        onSuccess={() => fetchProjects()}
      />

      <ProjectDetailDialog
        project={selectedProject}
        isOpen={showDetailDialog}
        onClose={() => {
          setShowDetailDialog(false)
          setSelectedProject(null)
        }}
      />
    </div>
  )
}